<?php

namespace lico\Tool;

class Thumb
{

    protected $config = [
        'allowExt' => ['gif', 'jpg', 'jpeg', 'png', 'wbmp'], //允许的图片格式
        'sourcePath' => '', //原图片路径
        'thumbFolder' => false, //缩略图路径文件夹,false将不保存，直接显示
        'filename' => '', //缩略图名
        'thumbType' => 1, //1比例缩放2固定长宽比例缩放3固定长宽
        'ratio' => 0.5, //类型为比例时
        'width' => 100, //类型为固定长宽时：缩略图宽
        'height' => 80, //类型为固定长宽时：缩略图宽
    ];

    protected $ext;
    protected $sourceCompletePath; //原图片完整路径
    protected $sourceWidth;
    protected $sourceHeight;
    protected $error;

    public function __construct($config)
    {
        $this->config = array_merge($this->config, $config);
    }

    /**
     * 设置错误
     */
    protected function setError($error)
    {
        $this->error = $error;
        return false;
    }

    /**
     * 获取错误
     */
    public function getError()
    {
        return $this->error;
    }

    /**
     * 检测图片后缀
     */
    public function checkExt()
    {

        if (!$this->config['sourcePath']) {
            return $this->setError('原图片路径不可为空');
        }
        $this->sourceCompletePath = $this->config['sourcePath'];
        if (!file_exists(@iconv('UTF-8', 'GB2312', $this->sourceCompletePath))) {
            return $this->setError('请检查原图片是否存在');
        }

        //获取原始图片长,宽,后缀
        $typeMap = [1 => 'GIF', 2 => 'JPG', 3 => 'PNG', 4 => 'SWF', 5 => 'PSD', 6 => 'BMP', 7 => 'TIFF(intel)',
        8 => 'TIFF(motorola)',9 => 'JPC', 10 => 'JP2', 11 => 'JPX', 12 => 'JB2', 13 => 'SWC', 14 => 'IFF',
        15 => 'WBMP', 16 => 'XBM'];
        $type = getimagesize($this->sourceCompletePath)[2];
        $ext = strtolower($typeMap[$type]);
        // p($ext);
        if (!in_array($ext, $this->config['allowExt'])) {
            return $this->setError('暂时只支持' . implode(',', $this->config['allowExt']) . '格式的图片,当前格式：' . $this->ext);
        }

        //待生成的缩略图的后缀
        $ext = $ext == 'jpg' ? 'jpeg' : $ext;

        //缩略图暂时只支持gif,jpeg,png,wbmp
        if (!in_array($ext, ['gif', 'jpeg', 'png', 'wbmp'])) {
            return $this->setError('缩略图只能是' . implode(',', ['gif', 'jpeg', 'png', 'wbmp']) . '格式,当前格式：' . $ext);
        }

        $this->ext = $ext;

        return true;
    }

    /**
     * 设置缩略图
     */
    public function draw()
    {

        $success = $this->checkExt();
        if (!$success) {
            return false;
        }

        //创建大图和小图的画布
        $method = "imagecreatefrom" . $this->ext;
        $bigCanvas = $method($this->sourceCompletePath);

        $exif = [];
        if (function_exists("exif_read_data")) { //需要开启exif扩展
            $exif = @exif_read_data($this->sourceCompletePath); //照片 设备信息
        }
        // 图片旋转还原
        if (!empty($exif['Orientation'])) {
            switch ($exif['Orientation']) {
                case 3: // 180 rotate left
                    $bigCanvas = imagerotate($bigCanvas, 180, 0);
                    break;
                case 6: // 90 rotate right
                    $bigCanvas = imagerotate($bigCanvas, -90, 0);
                    break;
                case 8: // 90 rotate left
                    $bigCanvas = imagerotate($bigCanvas, 90, 0);
                    break;
            }
        }
        $this->sourceWidth = imagesx($bigCanvas);
        $this->sourceHeight = imagesy($bigCanvas);

        //计算大图缩放后的大小信息
        $thumbExtName = ''; //缩略图追加名
        switch ($this->config['thumbType']) {
            case '1':
                $rate = $this->config['ratio'];
                $width = $this->sourceWidth * $rate;
                $height = $this->sourceHeight * $rate;
                $thumbExtName = $rate;
                break;
            case '2':
                $rate = min($this->config['width'] / $this->sourceWidth, $this->config['height'] / $this->sourceHeight);
                $width = $this->sourceWidth * $rate;
                $height = $this->sourceHeight * $rate;
                $thumbExtName = $this->config['width'];
                break;
            default:
                $width = $this->config['width'];
                $height = $this->config['height'];
                $thumbExtName = $width . '_' . $height;
                break;
        }

        $smallCanvas = imagecreatetruecolor($width, $height);
        //创建白色画笔,并给小图画布填充背景
        $white = imagecolorallocate($smallCanvas, 255, 255, 255);
        imagefill($smallCanvas, 0, 0, $white);

        //进行缩放
        if (function_exists("imagecopyresampled")) {
            imagecopyresampled($smallCanvas, $bigCanvas, 0, 0, 0, 0, $width, $height, $this->sourceWidth, $this->sourceHeight);
        } else {
            imagecopyresized($smallCanvas, $bigCanvas, 0, 0, 0, 0, $width, $height, $this->sourceWidth, $this->sourceHeight);
        }

        if ($this->config['thumbFolder']) {
            //保存成文件
            $thumbname = $this->config['filename'] . '.' . $this->ext;
            $thumb = strtr($this->config['thumbFolder'] . DS . $thumbname, '/', DS);
        } else {
            ob_clean();
            header('Content-type:image/' . $this->ext);
            $thumb = null;
        }
        // p($thumb);
        $method = "image" . $this->ext;
        $method($smallCanvas, $thumb);
        //销毁画布
        imagedestroy($bigCanvas);
        imagedestroy($smallCanvas);

        return $thumbname;
    }
}
